<template>
  <div class="bg-gray100 main">
    <div class="dis-flex flex-v100">
      <div class="title">编辑内容</div>
      <div class="tools bg-gray90 dis-flex flex-sbc">
        <div class="flex-atLeft btn-tab">
          <ToolsArea :tools="tools" @switchTool="taggleTool" @addEmoji="addEmoji">
          </ToolsArea>
        </div>
        <div class="flex-atRight" style="margin-right:300px;">
          <MaterialLibrary ref="materialLibrary"
            :canUseLibs="false" :tools="tools" @switchTab="taggleTool"
            :pid="''" :aid="0" :ceid="conditional.companyEmployeeId || 0"
            @getMaterialObject="getMaterial"
          >
          </MaterialLibrary>
        </div>
        <div class="mask" v-if="(step!=0)"></div>
      </div><!-- tools -->
      <div class="richtxt bg-gray95">
        <MsgEditArea ref="editArea" :msgType="msgType"></MsgEditArea>
        <div class="mask" v-if="(step!=0)"></div>
      </div><!-- richtxt -->
      <div class="targetApp bg-gray100">
        <AddTargert ref="targert"
          :workBenchList="workBenchList"
          :authorityLimited="authorityLimited"
          :targetArr="targetArr"
          @stepChange="stepChange">
        </AddTargert>
        <!-- 工作台/应用;权限;目标组 -->
        <!-- <div class="mask" v-if="(step!=1)"></div> -->
      </div>
      <SendMsg @readySend="useWorkbenchSendMsg"></SendMsg>
    </div>
  </div>
  
</template>

<script>
import { emoji,ruleStr,emojiReplace,ruleImg,imgReplaceEmoji } from '../../assets/emoticon.js';
import { mapState, mapMutations } from 'vuex';
export default {
  components:{
    MaterialLibrary:()=>{ return import('./../materialLibrary/index.vue') },
    ToolsArea:  ()=>{ return import('./1-toolsArea.vue')    },
    MsgEditArea:()=>{ return import('./2-msgEditArea.vue')  },
    AddTargert: ()=>{ return import('./3-addTargert.vue')   },
    SendMsg:    ()=>{ return import('./4-sendMsg.vue')      },
  },
  computed:{
    ...mapState([
      'conditional',//这里只有ceid(员工id)有用途
    ]),
    msgType:function(){
      return this.tools.find((v)=>{return v.isActive}).msgType
    },
  },
  provide(){
    return {
      pDraft:this.draft,
      mpnews:this.draft.mpnews.articles,
      serverUrl: 'http://upload.qiniup.com', //上传图片的地址
      qiniuaddr:'https://qiniuoss.chenxi618.com',
    }
  },
  data(){
    return{
      isDev:process.env.NODE_ENV== 'development',
      step:0,//步骤锁定1:素材选择,2目标选择,3发送动作
      tools:[
        {isActive:false,txt:''    ,icon:'icon-face'   ,msgType:'text',},//emoji
        {isActive:true,txt:'文字',icon:'icon-wenzi'  ,msgType:'text',  },
        {isActive:false,txt:'图文',icon:'icon-tuwen'  ,msgType:'mpnews',},
        {isActive:false,txt:'图片',icon:'icon-tupian' ,msgType:'image', },
        {isActive:false,txt:'视频',icon:'icon-shipin' ,msgType:'video', },
        {isActive:false,txt:'文件',icon:'icon-wenjian',msgType:'file',  },
      ],// 选素材类型
      draft:{
        text:'',
        mpnews:{
          id:'',articles:[]
        },
        image:{
          name:'',
          media_id:null,//空值需要二次请求
          imgUrl:'',//图片本体,七牛地址
        },
        video:{
          name:'',
          media_id:null,//空值需要二次请求
          imgUrl:'',//封面
          fileUrl:'',// 视频本体,七牛地址
        },
        file:{
          name:'',
          media_id:null,//空值需要二次请求
          fileUrl:'',// 文件本体,七牛地址
        },
      },// 草稿区,需要注意 MediaId
      workBenchList:[],//工作台/应用列表 mounted 就加载备用
      authorityLimited:{isAll:true,list:[],},// 获取素材同时获取应用选择的权限限制
      targetArr:[],//实际目标组
    }
  },
  methods:{
    stepChange:function(v){
      console.log('setpChange',v)
      this.step = v;
    },
    taggleTool:function(idx){
      this.tools.forEach((v,i)=>{v.isActive = ( idx === i );})
    },//切换工具/草稿内容
    getMaterial:function(cache){
      let self = this;//console.log(cache)
      this.$api.getMaterialContent(cache).then((res)=>{
        if(res.status == 200){
          let obj = res.data.data;
          // draft:{text:'',mpnews:[],image:{},video:{},file:{},},// 草稿区,需要注意 MediaId
          // console.log('单条素材的具体内容',obj)
          return obj;
        }else{
          throw '服务端异常';
        }
      }).then((res)=>{
        console.log('%c [ res ]', 'font-size:13px; background:pink; color:#bf2c9f;', res)
        if(self.msgType == 'text'){
          self.draft.text = res.content_Body
        };
        if(self.msgType == 'mpnews'){
          self.draft.mpnews.id = res.id;
          self.draft.mpnews.articles.splice(0,self.draft.mpnews.articles.length)
          res.articles.forEach((v)=>{
            self.draft.mpnews.articles.push(v)
          })
        };
        if(self.msgType == 'image'){
          self.draft.image.media_id = res.media_Id;
          self.draft.image.imgUrl   = res.imgUrl;
        }
        if(self.msgType == 'video'){
          self.draft.video.media_id = res.media_Id;
          self.draft.video.fileUrl  = res.video_Url;
        }
        if(self.msgType == 'file'){
          self.draft.file.media_id = res.media_Id;
          self.draft.file.fileUrl = res.file_Url;
          self.draft.file.mediaName = res.title;
          self.draft.file.name = res.title;
        }
        console.log(res)//素材本体
      }).catch((err)=>{
        console.error(err)
      })//获取素材本体
      this.$api.getMaterialAgent(cache).then((res)=>{
        console.log(res)
        // if(self.msgType == 'text'){return}
        if(res.data.code == 200){
          self.authorityLimited.isAll = false,
          self.authorityLimited.list.splice(0,self.authorityLimited.list.length)
          res.data.data.forEach((v)=>{
            self.authorityLimited.list.push(v);
          })
        }
      })
    },
    addEmoji:function(objEmoji){
      this.$refs.editArea.addEmoji(objEmoji)
    },
    useWorkbenchSendMsg:function(argTime){
      let arg0 = Object.assign(
        {companyEmployeeId:this.conditional.companyEmployeeId},
        argTime
      )
      let thisVue = this;
      console.log( '当前类型的消息本体:',thisVue.draft[thisVue.msgType] )
      let α = this.getAppGroup( this.$refs.targert.targatList ).map((v)=>{
        console.log(v)
        let arg = Object.assign(
          {esCompanyId:thisVue.$store.getters.getCEID.eSCompanyId},
          {"touser": "","toparty": "","totag": "",},v,
          // {"touser":"HFWQQ-2021111318343173518849137"},
          argTime,
          {
            "msgtype": thisVue.msgType,
            "text":null,"image":null,"video":null,"file":null,"mpnews":null,
            "markdown":null,
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 0
          },
        )
        return arg
      })//以 复数目标 为基础获取 对应的 复数的 参数 返回值为数组对象
      console.log('发送前参数(除了消息内容外的参数):',α)//[{},{}]
      switch (this.msgType){
        case 'text':
          thisVue.$axios.all(
            α.map((v)=>{
              console.log(v);//单个复合参数
              let arg1 = Object.assign(v,{
                text:{
                  content:imgReplaceEmoji(thisVue.draft.text).replace('<p>', '').replace('</p>', '')
                  .replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/<\/?[^>]*>/g,'')
                }
              })
              return thisVue.$api.sendMsg(arg0,arg1).then(res=>{console.log(res)})
            })
          ).then(res=>{
            console.log(res)
            thisVue.clearDraft()
          }).catch(err=>{
            console.error(err)
          })
          break;
        case 'image':
          thisVue.getDraftNeedMediaId().then((res)=>{
            console.log(res);// 返回带 k:v = esid:mid 的对象
            thisVue.$axios.all(
              α.map((v)=>{
                console.log(v);//单个复合参数//eSCompanyId
                let ckz = res.find((v2)=>{return v2.esCompanyId == v.esCompanyId});
                console.log(ckz)
                let con = {
                  image:{
                    media_id:ckz.media_Id,
                    imgUrl:ckz.qiniuUrl
                  }
                }
                let arg1 = Object.assign(v,con)
                return thisVue.$api.sendMsg(arg0,arg1).then(res=>{console.log(res)})
              })
            ).then(res=>{
              console.log(res)
              thisVue.clearDraft()
            }).catch(err=>{
              console.error(err)
            })
          })
          break;
        case 'video':
          thisVue.getDraftNeedMediaId().then((res)=>{
            console.log(res);// 返回带 k:v = esid:mid 的对象
            thisVue.$axios.all(
              α.map((v)=>{
                console.log(v);//单个复合参数//eSCompanyId
                let ckz = res.find((v2)=>{return v2.esCompanyId == v.esCompanyId});
                let con = {
                  video:{
                    media_id:ckz.media_Id,
                    title:ckz.mediaName,
                    description:'',
                    imgUrl:'',
                    fileUrl:ckz.qiniuUrl
                  }
                }
                let arg1 = Object.assign(v,con)
                return thisVue.$api.sendMsg(arg0,arg1).then(res=>{console.log(res)})
              })
            ).then(res=>{
              console.log(res)
              thisVue.clearDraft()
            }).catch(err=>{
              console.error(err)
            })
          })
          break;
        case 'file':
          thisVue.getDraftNeedMediaId().then((res)=>{
            console.log(res);// 返回带 k:v = esid:mid 的对象
            thisVue.$axios.all(
              α.map((v)=>{
                console.log(v);//单个复合参数//eSCompanyId
                let ckz = res.find((v2)=>{return v2.esCompanyId == v.esCompanyId});
                console.log(ckz)
                let con = {
                  file:{
                    media_id:ckz.media_Id,
                    mediaName:ckz.mediaName,
                    fileUrl:ckz.qiniuUrl
                  }
                }
                let arg1 = Object.assign(v,con)
                return thisVue.$api.sendMsg(arg0,arg1).then(res=>{console.log(res)})
              })
            ).then(res=>{
              console.log(res)
              thisVue.clearDraft()
            }).catch(err=>{
              console.error(err)
            })
          })
          break;
        case 'mpnews':
          thisVue.getDraftNeedMediaId().then((res)=>{
            console.log(res);// 返回带 k:v = esid:mid 的对象
            thisVue.$axios.all(
              α.map((v)=>{
                console.log(v);//单个复合参数//eSCompanyId
                let ckz = res.filter((v2)=>{return v2.esCompanyId == v.esCompanyId});
                let con = thisVue.draft.mpnews.articles.map((v3,i)=>{
                  v3.thumb_media_id = ckz[i].media_Id
                  return v3
                });
                console.log(con)
                let arg1 = Object.assign(v,{mpnews:{articles:con}})
                return thisVue.$api.sendMsg(arg0,arg1).then(res=>{console.log(res)})
              })
            ).then(res=>{
              console.log(res);
              thisVue.clearDraft()
            }).catch(err=>{
              console.error(err)
            })
          })
          break;
        default:
          break;
      }
      return;

    },
    getDraftNeedMediaId:function(){//期望返回带 k:v = esid:mid 的对象
      let att = this.$refs.targert.targatList;
      let orz;
      if(this.msgType == 'text'){ orz = []; }
      if(this.msgType == 'image'){
        orz = [{
          index:0,
          esCompanyId:'',
          qiniuUrl:this.draft.image.imgUrl,
          mediaType:'image',
          mediaName:this.draft.image.name
        }]
      }
      if(this.msgType == 'video'){
        orz = [{
          index:0,
          esCompanyId:'',
          qiniuUrl:this.draft.video.fileUrl,
          mediaType:'video',
          mediaName:this.draft.video.name
        }]
        console.log(orz)
      }
      if(this.msgType == 'file'){
        orz = [{
          index:0,
          esCompanyId:'',
          qiniuUrl:this.draft.file.fileUrl,
          mediaType:'file',
          mediaName:this.draft.file.mediaName
        }]
      }
      if(this.msgType == 'mpnews'){
        orz = this.draft.mpnews.articles.map((v,i)=>{
          return {
            index:i,
            esCompanyId:'',
            qiniuUrl:v.imgUrl,
            mediaType:'image',
            mediaName:'',
          }
        })
      }
      let αrguments = [];
      let pSet = [];// Promise 对象组
      let arrESID = this.getESidArr(att);//获取目标中esid的数组
      
      for( let i in arrESID){
        let esid = arrESID[i]
        for(let j in orz){
          orz[j].esCompanyId = esid
          αrguments.push(orz[j])
          pSet.push(
            (()=>{return this.$api.getGetMediaId(orz[j])})()
          )
        }
      }
      return this.$axios.all(pSet).then((res)=>{
        return αrguments.map((v,i)=>{
          v.media_Id = res[i].data.data;
          return v
        })
      })
    },
    getESidArr:function(arr) {
      let arrEsid = arr.reduce((t, v, i, a) => {
        if (t.includes(v[0].id)) {
          return t
        } else {
          return t.concat(v[0].id)
        }
      }, []);
      return arrEsid
    },
    getAppGroup:function(arr) {
      let α = arr.sort((a, b) => {
        if (a[0].id == b[0].id) {
          if (a[1].id == b[1].id) {
            return String(a[2].type).localeCompare(String(b[2].type))
          } else {
            return String(a[1].id).localeCompare(String(b[1].id))
          }
        } else {
          return String(a[0].id).localeCompare(String(b[0].id))
        }
      })//排序为后续的判断条件 (和上一条相符) 做基础
      let β = α.reduce((t, v, i, a) => {
        if (i == 0) {//第0条的手动处理
          t.push({ pid: v[0].id, aid: v[1].id, arr: [v[2]] })
          return t
        } else {//后续的参考尾条(t[t.length - 1])处理
          if ((v[0].id == t[t.length - 1].pid) && (v[1].id == t[t.length - 1].aid)) {
            t[t.length - 1].arr.push(v[2])
            return t
          } else {
            t.push({ pid: v[0].id, aid: v[1].id, arr: [v[2]] })
            return t
          }//相符推入子节点,不符则创建新的尾条,因为排序后,下一条数据不会和之前的数据再有交集故只需要判断尾条
        }
      }, [])
      β.forEach((item) => {
        item.tree = []; item.leaf = []; item.label = [];item.all = false;
        item.arr.forEach((v) => {
          console.log(v)
          switch (v.type){
            case 'tree':
              item.tree.push(v.id)
              break;
            case 'leaf':
              item.leaf.push(v.id)
              break;
            case 'label':
              console.log(v.group)
              v.group.reduce((t1,v1,i1,a1)=>{
                return t1.concat(v1.id)
              },[]).forEach((v2)=>{
                item.label.push(v2)
              })
              break;
            case '@all':
              item.all = true;
              break;
            default:
              return;
          }
        })
      });//二次加工
      let γ = β.reduce((t, v, i, a) => {
        console.log(v)
        if (v.all > 0) {
          t.push({
            esCompanyId: v.pid,
            agentid: v.aid,
            touser: '@all',
          })
        }
        if (v.leaf.length > 0) {
          t.push({
            esCompanyId: v.pid,
            agentid: v.aid,
            touser: v.leaf.sort((a, b) => { return a - b }).join("|"),
          })
        }
        if (v.tree.length > 0) {
          t.push({
            esCompanyId: v.pid,
            agentid: v.aid,
            toparty: v.tree.sort((a, b) => { return a - b }).join("|"),
          })
        }
        if (v.label.length > 0) {
          t.push({
            esCompanyId: v.pid,
            agentid: v.aid,
            totag: v.label.sort((a, b) => { return a - b }).join("|"),
          })
        }
        return t
      }, [])//三次加工
      return γ
    },
    clearDraft:function(type){
      if(['text','image','video','file','mpnews'].includes(type)){
        this.$refs.editArea.clearDraft(type);
      }else{
        this.$refs.editArea.clearDraft("text");
        this.$refs.editArea.clearDraft("image");
        this.$refs.editArea.clearDraft("video");
        this.$refs.editArea.clearDraft("file");
        this.$refs.editArea.clearDraft("mpnews");
        this.$refs.targert.clearTargets();
        this.step = 0;
      }
    },
  },
  mounted(){
    this.$bus.$on()
    let self = this;
    const opt = {
      companyEmployeeId:this.conditional.companyEmployeeId,
      eSCompanyId: '',agentid:0,searchName:'',
      state:0,page:1,size:10
    }//收集请求工作台应用用的参数;
    console.log(opt)
    this.$api.get_App_Cus(opt).then((res)=>{
      if(res.data.code == 200){
        res.data.data.workBenches.workBenchList.forEach((item) => {
          // console.log(item)
          self.workBenchList.push({
            id:item.eSCompanyId,
            name:item.companyName,
            list:item.agentList,
          })
        });
      }
    }).catch((err)=>{
      if(self.isDev){
        this.$message({type: 'warning',message: '没有收到来着后端的工作台/应用',});
      }else{
        console.error(err)
      }
    })//发送请求收取工作台/应用,等素材库获取二筛后重组
  }
}
</script>

<style lang="less" scoped>
@import url('../../assets/config.less');
@import url('../../assets/style.less');
.mask{
  position: absolute;
  top:0;bottom:0;left:0;right:0;
  z-index:7;
  background-color:rgba(128,128,128,0.7);
  cursor:not-allowed;
}
.main{
  padding:unit(@defPadding,px);
}
.title,.targetApp,.tools,.richtxt,.sendOut{
  border-top: @defBorder;
  border-left: @defBorder;
  border-right: @defBorder;
}
.title{
  flex:0 0 56px;
  padding:0 16px;
  line-height:56px;
}
.targetApp{
  flex:0 0 44px;
  padding:0 16px;
}
.tools{
  @h:44px;
  flex:0 0 @h;
  line-height:@h;
  padding:0 16px;
  .btn{
    font-size:14px;
    color:#999;
    &::before{
      font-size: 16px;
      margin-right:0.5em;
    }
    &.active{
      color:@blue;
    }
    &+.btn{
      margin-left:10px;
    }
  }
}
.richtxt{
  flex:1 1 40%;
  height:40%;
}

</style>